import moment from 'moment';
import React, { useEffect, useMemo, useState } from 'react';
import { formatDuration } from '../../../../utils/time';
/**
 * 订单列表倒计时文本组件
*/
export const OrderDownTime = (props) => {
    const { time, renderBeforeTime, renderOverTime, record } = props;
    const resolveTime = useMemo(() => moment(time), [time]);
    const [diffTimeStr, setDiffTimeStr] = useState('');
    function exec() {
      const now = moment();
      let res = '';
      if (resolveTime.isBefore(now)) {
        const invalidTime = record?.invalidTime // 作废时间
        const deliveryTime = record?.logisticsList?.[0]?.deliveryTime // 发货时间
        const comparisonTimer = record?.state === 50 ? invalidTime : record?.state === 40 ? deliveryTime : moment();
        const duration = moment.duration(moment(comparisonTimer).diff(resolveTime));
        if (duration?._milliseconds > 0) { // 已作废订单如果已作废时间小于最晚发货时间会时一个负数
          const durationStr = formatDuration(duration);
          res = durationStr ? renderOverTime(durationStr) : '';
        } else {
          res = ''
        }
      } else if (resolveTime.isAfter(now)) {
        const duration = moment.duration(resolveTime.diff(now));
        const durationStr = formatDuration(duration);
        res = durationStr ? renderBeforeTime(durationStr) : '';
      } else {
        res = '';
      }
      setDiffTimeStr(res);
      startDownTime();
    }
    function startDownTime() {
      setTimeout(() => {
        exec();
      }, 5000);
    }
    useEffect(() => {
      if (time) {
        exec();
        startDownTime();
      }
    }, [time]);
    if (!time) {
      return null;
    }
    return diffTimeStr;
};
